package com.flyxteam.learner.springboot.web.controller;

import javax.annotation.*;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.*;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.flyxteam.learner.springboot.ApplicationConfig;

// ## 使用@SpringBootTest替代传统的@ContextConfiguration
@SpringBootTest(classes = ApplicationConfig.class)
@WebAppConfiguration
@Rollback
@RunWith(SpringJUnit4ClassRunner.class)
// ## 测试基类，用法同SpringMvc的mock
public abstract class JUnitTestSupport {

    MockMvc mockMvc;
    MockHttpServletRequest mockRequest;
    MockHttpServletResponse mockResponse;
    MockHttpSession mockSession;

    // 注入WebApplicationContext
    @Autowired
    WebApplicationContext webApplicationContext;
    
    // 构造MockMvc
    @PostConstruct
    public void afterContextInit() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        mockRequest = new MockHttpServletRequest();
        mockRequest.setCharacterEncoding("UTF-8");
        mockResponse = new MockHttpServletResponse();
        mockResponse.setCharacterEncoding("UTF-8");
    }
    
}
